import {
	setCid
} from "@/api/customApi.js"

export function Authorized() {
	// 判断用户是否开启推送权限，如果没有则引导引导用户跳转app设置页
	if (uni.getAppAuthorizeSetting().notificationAuthorized === "denied") {
		uni.showModal({
			title: '提示',
			content: '未开启推送权限，点击确定前往开启',
			success: function(res) {
				if (res.confirm) {
					uni.openAppAuthorizeSetting()
				}
			}
		});
	}

	const userInfo = uni.getStorageSync('userInfo')
	// 获取客户端唯一的推送标识
	uni.getPushClientId({
		success: (res) => {
			// 判断是否有用户信息
			if (userInfo) {
				setCid({
					email: userInfo.email,
					phone: userInfo.phone,
					userId: userInfo.userId,
					userName: userInfo.userName,
					userNameCN: userInfo.userNameCN,
					cid: res.cid
				})
			}
		},
		fail(err) {
			console.log(err)
		}
	})

	//启动推送事件监听
	uni.onPushMessage((res) => {
		const {
			type,
			data
		} = res
		if (type === "click") {
			const datas = JSON.stringify(data.payload)
			uni.navigateTo({
				url: `/pages/appPages/appPages?route=${data.payload.url||data.payload}&datas=${datas}`
			})
		} else if (type === "receive") {
			uni.createPushMessage({
				title: data.title,
				content: data.content,
				payload: data.payload
			})
		}
	});
}